//
//  ZTacticsViewController.m
//  DoctorFAQs
//
//  Created by zjq on 17/2/20.
//  Copyright © 2017年 zjq. All rights reserved.
//

#import "ZTacticsViewController.h"
#import "ZLookSearchView.h"
#import "ZTacticsTableViewCell.h"
#import "ZTacticsDetailViewController.h" //详情界面
#import "ZDoctorViewController.h"// 医生界面
#import "ZTDSearchViewController.h"
#import "DoctorModel.h"
#import "LZTacticsModel.h"
#import "SPPlaceholderCell.h"
static NSString *const placeCellID = @"placeholders";
static NSString * const KJTacticsTableViewIdentifier = @"JTacticsTableViewIdentifier";
// 分页数据
static int _page = 1;

@interface ZTacticsViewController ()<UITableViewDelegate,UITableViewDataSource>{
    ZLookSearchView * _headView;
}
/** 数据数组 */
@property (nonatomic, strong) NSMutableArray *listArr;
/** 医生模型数组 */
@property (nonatomic, strong) NSMutableArray *doctorArr;
/** 标题类型数组 */
@property (nonatomic, strong) NSMutableArray <LZTacticsModel *>*itemArr;

@property (nonatomic,strong) UITableView * mainTabview;// 主表格视图
@property (nonatomic,assign) BOOL isHaveData;
@end

@implementation ZTacticsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationItem.title = @"就医策略";
    self.view.backgroundColor = [UIColor whiteColor];
    [self initialzeDatas];
    [self initlizeInterface];
    _listArr = [NSMutableArray array];
    _doctorArr = [NSMutableArray array];
    _itemArr = [NSMutableArray array];
    [_mainTabview.mj_header beginRefreshing];
}
- (void)initialzeDatas {
    self.isHaveData = YES;
}
- (void)initlizeInterface {
    _headView = [[ZLookSearchView alloc] init];
    _headView.backgroundView.backgroundColor = MYGRAYCOLOR;
    [_headView.searchBtn  addTarget:self action:@selector(jumpZTDSearchVC) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_headView];
    [self.view addSubview:self.mainTabview];
    [_headView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.width.equalTo(self.view);
        make.height.offset(50*ysIZE);
    }];
    [self.mainTabview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.width.bottom.equalTo(self.view);
        make.top.equalTo(_headView.mas_bottom);
    }];
}
// 表格视图协议
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.isHaveData == YES?  _itemArr.count:1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    __weak typeof(self) weakSelf = self;
    if (self.isHaveData == YES) {
        ZTacticsTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:KJTacticsTableViewIdentifier forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.doctorModel = _doctorArr[indexPath.row];
        cell.tacticsModel = _itemArr[indexPath.row];
        cell.GoDFBlock = ^() {
            [weakSelf joinDoctorVCWithRow:indexPath.row];
        };
        return cell;
    }else {
        SPPlaceholderCell *cell = [tableView dequeueReusableCellWithIdentifier:placeCellID];
        return cell;
    }
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.isHaveData == NO) {
        return;
    }
    ZTacticsDetailViewController * ZTDVC = [[ZTacticsDetailViewController alloc] init];
    ZTDVC.artId = _itemArr[indexPath.row].artID;
    [self.navigationController pushViewController:ZTDVC animated:YES];
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.isHaveData == YES) {
        return 260*ysIZE;
    }else {
        return  SCREEN_Height-104;
    }
}
// 跳转医生主页
- (void)joinDoctorVCWithRow:(NSInteger)row {
    ZDoctorViewController * vc = [[ZDoctorViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

// 跳转到搜索详情
- (void)jumpZTDSearchVC {
    ZTDSearchViewController * ZTDSVC = [[ZTDSearchViewController alloc] init];
    [self.navigationController pushViewController:ZTDSVC animated:YES];
}

//lazy
- (UITableView *)mainTabview {
    if (_mainTabview) {
        return _mainTabview;
    }
    _mainTabview = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    _mainTabview.delegate = self;
    _mainTabview.dataSource = self;
//    _mainTabview.rowHeight = 260*ysIZE;
    _mainTabview.separatorStyle = NO;
    _mainTabview.showsVerticalScrollIndicator = NO;
     [_mainTabview registerNib:[UINib nibWithNibName:NSStringFromClass([SPPlaceholderCell class]) bundle:nil] forCellReuseIdentifier:placeCellID];
    [_mainTabview registerClass:[ZTacticsTableViewCell class] forCellReuseIdentifier:KJTacticsTableViewIdentifier];
    [self loadMoreData];
    [self refreshData];
    return _mainTabview;
}

// 下拉刷新
- (void)refreshData {
    __weak typeof(self) weakSelf = self;
    _mainTabview.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [weakSelf pullDownData];
        [weakSelf.mainTabview.mj_header endRefreshing];
    }];
}

// 上拉加载
- (void)loadMoreData {
    __weak typeof(self) weakSelf = self;
    _mainTabview.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        [weakSelf pullUpData];
        [weakSelf.mainTabview.mj_footer endRefreshing];
    }];
}

// 下拉刷新方法
- (void)pullDownData {
    _page = 1;
    [YJProgressHUD showProgress:@"努力加载中..." inView:self.view];
    NSDictionary *paramas = @{@"p":[NSString stringWithFormat:@"%d",_page]};
    __weak typeof(self) weakSelf = self;
    self.isHaveData = YES;
    [BaseRequest requestWithMethodResponseJsonByGet:TestURL paramars:paramas paramarsSite:@"Index/strategy" sucessBlock:^(id content) {
        NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:content options:NSJSONReadingMutableContainers error:nil];
        LZLog(@"---就医策略下拉刷新数据---%@",dict);
        if ([dict[@"code"] intValue] == 0) {
            self.isHaveData = NO;
            [self.mainTabview reloadData];
            [YJProgressHUD showMessage:@"刷新失败" inView:self.view];
        }else if ([dict[@"code"] intValue] == 1) {
            [YJProgressHUD showMessage:@"刷新成功" inView:self.view];
            // 赋值
            [weakSelf setValueWithDict:dict];
        }
    } failure:^(NSError *error) {
        self.isHaveData = NO;
        [self.mainTabview reloadData];
        [YJProgressHUD showMessage:@"刷新失败" inView:self.view];
        
    }];
    
}

// 上拉加载方法
- (void)pullUpData {
    [YJProgressHUD showProgress:@"努力加载中..." inView:self.view];
    _page ++;
    NSDictionary *paramas = @{@"p":[NSString stringWithFormat:@"%d",_page]};
    __weak typeof(self) weakSelf = self;
    [BaseRequest requestWithMethodResponseJsonByGet:TestURL paramars:paramas paramarsSite:@"Index/strategy" sucessBlock:^(id content) {
        NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:content options:NSJSONReadingMutableContainers error:nil];
        LZLog(@"就医策略上拉数据-------%@",dict);
        if ([dict[@"code"] intValue] == 0) {
            [YJProgressHUD showMessage:@"加载失败" inView:self.view];
        }else if ([dict[@"code"] intValue] == 1) {
            [YJProgressHUD showMessage:@"加载成功" inView:self.view];
            //NSArray *array =  [NSArray array];
            _listArr = dict[@"list"];
            [weakSelf dealDataWithArray:_listArr];
            // 赋值
//            [weakSelf setValueWithDict:dict];
//            [weakSelf.mainTabview reloadData];
        }
        
    } failure:^(NSError *error) {
        [YJProgressHUD showMessage:@"加载失败" inView:self.view];
    }];
}

// 拿到数据以后转为模型放进数组中
- (void)setValueWithDict:(NSDictionary *)dict {
    [_mainTabview.mj_footer resetNoMoreData];
    _listArr = dict[@"list"];
    if (_listArr.count == 0 ) {
        self.isHaveData = NO;
    }
    [_doctorArr removeAllObjects];
    [_itemArr removeAllObjects];
    for (NSDictionary *dict in _listArr) {
        DoctorModel *doctorItem = [[DoctorModel alloc] initWithDict:[dict mutableCopy]];
        [_doctorArr addObject:doctorItem];
        
        LZTacticsModel *tactisItem = [[LZTacticsModel alloc] initWithDict:[dict mutableCopy]];
        [_itemArr addObject:tactisItem];
    }
    [_mainTabview reloadData];
}


// 上拉加载后处理数据
- (void)dealDataWithArray:(NSArray *)array {
    [_mainTabview.mj_footer resetNoMoreData];
    if (array.count == 0) {
        [YJProgressHUD showMessage:@"没有更多数据了~" inView:self.view];
        [_mainTabview.mj_footer endRefreshingWithNoMoreData];

    }else if (array.count < 10) {
        [YJProgressHUD showMessage:@"刷新成功" inView:self.view];
        [_mainTabview.mj_footer endRefreshingWithNoMoreData];
    }
    for (NSDictionary *dict in array) {
        DoctorModel *doctorModel = [[DoctorModel alloc]initWithDict:[dict mutableCopy]];
        [_doctorArr addObject:doctorModel];
        
        LZTacticsModel *tacticsmodel = [[LZTacticsModel alloc] initWithDict:[dict mutableCopy]];
        [_itemArr addObject:tacticsmodel];
    }
    [_mainTabview reloadData];
}

@end
